<template>
  <basic-container>
    <el-row style="margin-bottom: 20px">
      <el-button size="small" @click="returnlast()">返回</el-button>
      <el-button
        size="small"
        v-if="showSubmit"
        :loading="buttonLoading"
        type="primary"
        @click="submit()"
        >提交</el-button
      >
    </el-row>

    <el-descriptions class="margin-top" title="询价单信息" :column="2" border>
      <el-descriptions-item>
        <template slot="label"> 标题 </template>
        {{ form.title }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 发票号 </template>
        {{ form.invoiceNumber }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 货物级别 </template>
        {{ form.goodsClass }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 起运港 </template>
        {{ form.departurePort }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 货物名称 </template>
        {{ form.cpmc }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 目的港 </template>
        {{ form.destinationPort }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 毛重（KGS）/柜（罐） </template>
        {{ form.grossWeight }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 船期_ETD </template>
        {{ form.shipDurationEtd }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 起运港（箱使.天） </template>
        {{ form.departurePortTime }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 船期_ETA </template>
        {{ form.shipDurationEta }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 目的港（箱使.天） </template>
        {{ form.destinationPortTime }}
      </el-descriptions-item>

      <el-descriptions-item>
        <template slot="label"> 其他要求 </template>
        {{ form.otherRequirements }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 合同号 </template>
        {{ form.contractNo }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 包装类型 </template>
        {{ form.packageType }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 箱量 </template>
        {{ form.containerCapacity }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 包装数量（桶/柜） </template>
        {{ form.packagesNumber }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 箱型 </template>
        {{ form.containerType }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 询价响应截止时间 </template>
        <!-- {{ form.endTime }} -->
        <el-date-picker
          :disabled="
            form.quoteStatus === 'finish' ||
            !vaildData(permission.tms_inquiry_modification_time, false)
          "
          v-model="form.endTime"
          :clearable="false"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          @change="timeChange"
          placeholder="选择日期时间"
        >
        </el-date-picker>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 询价有效期 </template>
        <!-- {{ form.effectiveTime }} -->
        <el-date-picker
          :disabled="
            form.quoteStatus === 'finish' ||
            !vaildData(permission.tms_inquiry_modification_time, false)
          "
          v-model="form.effectiveTime"
          :clearable="false"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          @change="timeChange"
          placeholder="选择日期时间"
        >
        </el-date-picker>
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 询价备注 </template>
        {{ form.remark }}
      </el-descriptions-item>
      <el-descriptions-item v-if="form.annex">
        <template slot="label"> 附件 </template>
        <div v-for="url in form.annex.split(',')" :key="url">
          <el-link
            :href="url"
            type="primary"
            target="_blank"
            icon="el-icon-download"
            >{{ url }}</el-link
          >
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <h4>报价信息</h4>
    <el-divider></el-divider>
    <avue-crud
      ref="crud"
      :table-loading="loading"
      :data="data"
      :option="option"
      :permission="getpermission"
      @on-load="tableonLoad"
    >
      <template slot="shippingDateETD" slot-scope="{ row }">
        {{ row.shippingDateETD }}
      </template>
      <template slot="scheduleEta" slot-scope="{ row }">
        {{ row.scheduleEta }}
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-button
          type="text"
          icon="el-icon-delete"
          v-if="getpermission('closeBtn', row)"
          size="small"
          @click="closelist(row)"
          tip="管理员"
          >关闭</el-button
        >
        <el-button
          type="text"
          icon="el-icon-date"
          size="small"
          v-if="getpermission('historicalBtn', row)"
          @click="historicalquotation(row)"
          tip="管理员"
          >历史议价</el-button
        >
        <el-button
          type="text"
          icon="el-icon-edit"
          size="small"
          v-if="getpermission('modifyBtn', row)"
          @click="adminmodifyquotation(row)"
          tip="管理员"
          >修改报价</el-button
        >
        <el-button
          type="text"
          icon="el-icon-finished"
          size="small"
          v-if="getpermission('confirmBtn', row)"
          @click="confirmwin(row)"
          tip="管理员"
          >确认中标</el-button
        >
        <el-button
          type="text"
          icon="el-icon-close"
          size="small"
          v-if="getpermission('confirmBtn', row)"
          @click="didNotWinTheBid(row)"
          tip="管理员"
          >未中标</el-button
        >
        <!-- <el-button
          type="text"
          icon="el-icon-edit"
          size="small"
          v-if="getpermission('detailbarrieradminBtn', row)"
          @click="barrierdetailadmin(row)"
          tip="管理员"
          >报价详情</el-button
        > -->
        <el-button
          type="text"
          icon="el-icon-edit"
          size="small"
          v-if="getpermission('detailbarrierBtn', row)"
          @click="barrierdetail(row)"
          >报价详情</el-button
        >
      </template>
    </avue-crud>
    <h4
      v-if="
        vaildData(permission.foreign_itemDetails_quotation_information, false)
      "
    >
      承运商明细
    </h4>
    <el-divider></el-divider>
    <avue-crud
      ref="carrierCrud"
      :table-loading="carrierLoading"
      :data="carrierData"
      :option="carrierOption"
      @on-load="carrierTableonLoad"
      v-if="
        vaildData(permission.foreign_itemDetails_quotation_information, false)
      "
    >
    </avue-crud>
    <el-divider></el-divider>
    <barrierDetail ref="barrierDetail" :ids="ids"></barrierDetail>
    <historicalBarrier
      ref="historicalBarrier"
      :modifyData="modifyData"
      :identity="identity"
    ></historicalBarrier>
    <bargainingHistorical
      ref="bargainingHistorical"
      :historyids="historyids"
    ></bargainingHistorical>
  </basic-container>
</template>

<script>
import { getDetail } from "@/api/inquiry/carrierDialog";
import { updateDate, submitOA } from "@/api/inquiry/index";
import {
  getListManage,
  closeList,
  getListCarrier,
  makesure,
  didNotWinTheBid,
  admingetListCarrier,
} from "@/api/inquiry/domestictrade/index";
import { mapGetters } from "vuex";
import barrierDetail from "./components/barrierDetail.vue";
import {
  getListbarrierDetail,
  InquirySheetCarrier,
} from "@/api/inquiry/foreigntrade/index";
import historicalBarrier from "./components/historicalBarrier.vue";
import bargainingHistorical from "./components/bargainingHistorical.vue";
export default {
  components: {
    barrierDetail,
    historicalBarrier,
    bargainingHistorical,
  },
  data() {
    return {
      query: {},
      form: {},
      data: [],
      carrierData: [],
      loading: false,
      carrierLoading: false,
      buttonLoading: false,
      ids: {},
      ranking: true,
      modifyData: null,
      identity: {},
      historyids: {},
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    option() {
      let option = {
        calcHeight: 30,
        align: "center",
        headerAlign: "center",
        index: this.ranking,
        indexLabel: "排名",
        border: true,
        searchLabelWidth: 120,
        searchMenuSpan: 6,
        menuWidth: 400,
        tip: false,
        viewBtn: false,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        editBtn: false,
        delBtn: false,
        labelWidth: 120,
        column: [
          {
            label: "承运商",
            prop: "carrierName",
          },
          {
            label: "状态",
            prop: "quotationStatus",
            display: false,
            hide: this.getpermission("showdatastatus"),
          },
        ],
      };
      //判断是否是管理员账号
      if (this.permission.foreign_itemDetails_quotation_information) {
        option.column = [
          {
            label: "承运商",
            prop: "carrierName",
          },
          {
            label: "状态",
            prop: "quotationStatus",
            display: false,
            hide: this.getpermission("showdatastatus"),
          },
          {
            label: "船公司",
            prop: "shippingCompany",
            rules: [
              { required: true, trigger: "blur", message: "船公司不能为空" },
            ],
          },
          {
            label: "合计",
            prop: "total",
            editDisabled: true,
          },
          {
            label: "海运费（USD）",
            prop: "shippingFee",
            labelWidth: 140,
            controls: false,
            type: "number",
            rules: [
              {
                required: true,
                trigger: "blur",
                message: "海运费不能为空,且必须为数字",
              },
            ],
          },
          {
            label: "港杂费（CNY）",
            prop: "portCharges",
            labelWidth: 140,
            controls: false,
            type: "number",
            rules: [
              {
                required: true,
                trigger: "blur",
                message: "港杂费不能为空,且必须为数字",
              },
            ],
          },
          {
            label: "船期_ETD",
            slot: true,
            prop: "shippingDateETD",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            mock: {
              type: "datetime",
              format: "yyyy-MM-dd",
            },
            rules: [
              { required: true, trigger: "blur", message: "船期_ETD不能为空" },
            ],
          },
          {
            label: "船期_ETA",
            slot: true,
            prop: "scheduleEta",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            mock: {
              type: "datetime",
              format: "yyyy-MM-dd",
            },
            rules: [
              { required: true, trigger: "blur", message: "船期_ETA不能为空" },
            ],
          },
          {
            label: "起运港(箱使/天)",
            prop: "departurePortBoxAngel",

            labelWidth: 140,
            rules: [
              {
                required: true,
                trigger: "blur",
                message: "起运港(箱使/天)不能为空",
              },
            ],
          },
          {
            label: "目的港(箱使/天)",
            labelWidth: 140,
            prop: "destinationPortBoxAngel",
            rules: [
              {
                required: true,
                trigger: "blur",
                message: "目的港(箱使/天)不能为空",
              },
            ],
          },
          {
            label: "是否直达",
            prop: "isItDirect",
            rules: [
              { required: true, trigger: "blur", message: "是否直达不能为空" },
            ],
          },
          {
            label: "报价说明",
            prop: "quoteDescription",
          },
        ];
      } else {
        option.column = [
          {
            label: "承运商",
            prop: "carrierName",
          },
          {
            label: "状态",
            prop: "quotationStatus",
            display: false,
            hide: this.getpermission("showdatastatus"),
          },
        ];
      }
      return option;
    },
    carrierOption() {
      return {
        calcHeight: 30,
        align: "center",
        headerAlign: "center",
        index: this.ranking,
        indexLabel: "序号",
        border: true,
        searchLabelWidth: 120,
        searchMenuSpan: 6,
        menuWidth: 400,
        tip: false,
        viewBtn: false,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        editBtn: false,
        delBtn: false,
        menu: false,
        labelWidth: 120,
        column: [
          {
            label: "承运商",
            prop: "carrierName",
          },
          {
            label: "状态",
            prop: "quotationStatus",
          },
        ],
      };
    },
    showSubmit() {
      let date = new Date().getTime();
      let endTime = new Date(this.form.endTime).getTime();
      return this.form.quoteStatus !== "finish" && date > endTime;
    },
  },
  methods: {
    getpermission(key, row) {
      switch (key) {
        case "closeBtn":
          return (
            this.permission.foreign_close_offer_m &&
            row.quotationStatus != "已作废" &&
            row.quotationStatus != "已完成"
          );
        case "showdatastatus":
          return !this.permission.foreign_domestictrade_detail_m;
        case "detailbarrieradminBtn":
          return this.permission.foreign_detailbarrier_m;
        case "detailbarrierBtn":
          return this.permission.foreign_detailbarrier && row.isNotMy;
        case "modifyBtn":
          return (
            this.permission.foreign_itemDetails_quotation_information &&
            this.permission.foreign_modify_quotation_m &&
            (row.quotationStatus == "待确认" ||
              row.quotationStatus == "待接受") &&
            this.ranking
          );
        case "confirmBtn":
          return (
            this.permission.foreign_itemDetails_quotation_information &&
            this.permission.foreign_confirm_winning_m &&
            (row.quotationStatus == "待确认" ||
              row.quotationStatus == "待接受") &&
            this.ranking
          );
        case "historicalBtn":
          return (
            this.permission.foreign_itemDetails_quotation_information &&
            this.permission.foreign_historical_bargaining_m
          );
        default:
          break;
      }
      return true;
    },
    closelist(row) {
      this.loading = true;
      closeList({ id: row.id }).then(() => {
        this.$message.success("操作成功");
        this.tableonLoad();
      });
    },
    tableonLoad(page, params = {}) {
      this.loading = true;
      //判断是否是管理员账号
      let getList = this.permission.foreign_itemDetails_quotation_information
        ? getListbarrierDetail
        : getListManage;
      getList(Object.assign(params, this.query)).then((res) => {
        this.loading = false;
        this.data = res.data.data;
        this.$refs.crud.doLayout();
      });
    },
    carrierTableonLoad() {
      this.carrierLoading = true;
      InquirySheetCarrier({ id: this.query.id }).then((res) => {
        this.carrierLoading = false;
        this.carrierData = res.data.data;
        this.$refs.carrierCrud.doLayout();
      });
    },
    barrierdetailadmin(row) {
      this.ids = {
        id: this.form.id,
        carrierId: row.carrierId,
        needsID: row.id,
        showStatus: row.quotationStatus,
        menushow: row.quotationStatus,
        ranking: this.ranking,
      };
      // console.log("管理员", this.ids);
      this.$refs.barrierDetail.open(row, {
        callback: (res) => {
          if (res === "refresh") {
            this.tableonLoad();
          }
        },
      });
    },
    barrierdetail(row) {
      this.ids = {
        id: this.form.id,
        carrierId: row.carrierId,
        needsID: row.id,
        showStatus: row.quotationStatus,
        menushow: row.quotationStatus,
        ranking: this.ranking,
      };
      // console.log("承运商", this.ids);
      this.$refs.barrierDetail.open(row, {
        callback: (res) => {
          if (res === "refresh") {
            this.tableonLoad();
          }
        },
      });
    },
    returnlast() {
      this.$router.$avueRouter.replace("/inquiry/foreigntrade/index");
    },
    onLoad(query) {
      getDetail(query).then((res) => {
        this.form = res.data.data;
        if (
          new Date().getTime() >= new Date(res.data.data.endTime).getTime()
            ? true
            : false
        ) {
          this.ranking = true;
          return;
        }
        this.ranking = false;
      });
    },
    historicalquotation(row) {
      this.historyids = {
        id: row.id,
      };
      this.$refs.bargainingHistorical.open(row, {
        callback: () => {},
      });
    },
    modifyquotation(row) {
      this.modifyData = row;
      this.identity = {
        isManagement: false,
        showoff: { display: "none" },
        barriershowoff: { display: "" },
      };
      this.$refs.historicalBarrier.open(row, {
        callback: (res) => {
          getListCarrier({ id: res.id, startId: res.id }, res).then(() => {
            this.$message.success("操作成功");
            this.$refs.historicalBarrier.close();
            this.tableonLoad();
          });
        },
      });
    },
    adminmodifyquotation(row) {
      this.modifyData = row;
      this.identity = {
        isManagement: true,
        barriershowoff: { display: "none" },
        showoff: { display: "" },
        quotedPrice: row.quotedPrice,
      };
      this.$refs.historicalBarrier.open(row, {
        callback: (res) => {
          admingetListCarrier({ id: res.id, startId: res.id }, res).then(() => {
            this.$message.success("操作成功");
            this.$refs.historicalBarrier.close();
            this.tableonLoad();
          });
        },
      });
    },
    // 确定中标
    confirmwin(row) {
      this.loading = true;
      this.$prompt("请输入中标箱量", "中标箱量", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^[1-9]\d*$/,
        inputErrorMessage: "请输入中标箱量",
      })
        .then(({ value }) => {
          makesure({ id: row.id, winningBoxQuantity: value }).then(() => {
            this.$message.success("操作成功");
            this.tableonLoad();
          });
        })
        .catch(() => {
          this.loading = false;
        });
      // makesure({ id: row.id }).then(() => {
      //   this.$message.success("操作成功");
      //   this.tableonLoad();
      // });
    },
    // 未中标
    didNotWinTheBid(row) {
      this.loading = true;
      didNotWinTheBid({ id: row.id }).then(() => {
        this.$message.success("操作成功");
        this.tableonLoad();
      });
    },
    // 修改询价响应日期和截止日期
    timeChange() {
      updateDate({
        id: this.form.id,
        endTime: this.form.endTime,
        effectiveTime: this.form.effectiveTime,
      })
        .then(({ data }) => {
          if (data.code === 200 && data.success) {
            this.$message.success(data.msg);
            this.onLoad(this.query);
            this.tableonLoad();
            this.carrierTableonLoad();
          }
        })
        .catch(() => {
          this.onLoad(this.query);
        });
    },
    //提交OA
    submit() {
      this.buttonLoading = true;
      submitOA(this.form.id)
        .then(({ data }) => {
          if (data.code === 200 && data.success) {
            this.buttonLoading = false;
            this.$message.success(data.msg);
            this.onLoad(this.query);
          }
        })
        .catch(() => {
          this.buttonLoading = false;
        });
    },
  },
  created() {
    this.query = {
      id: this.$route.query.id,
    };
    this.onLoad(this.query);
  },
};
</script>

<style></style>
